// pages/input/input.js
var Bmob = require('../../dist/Bmob-1.6.0.min.js');
const {
  $Toast
} = require('../../dist/base/index');
const {
  $Message
} = require('../../dist/base/index');
var app = getApp()
Page({
  data: {
    content: '',
    title: '',

    files: [],
    file_urls: [],

    oneChecked: false,
    tags: [],
    randomColor: [],
    num: 0,
    length: 0,
    flag: false
  },

  onLoad: function (options) {
    var tags = []
    let that = this;
    //从Bmob获取所有标签
    const query = Bmob.Query("label");
    query.select("tag");
    query.find().then(res => {
      for (var i = 0; i < res.length; i++) {
        tags.push({
          name: res[i].tag,
          checked: false,
          objectId: res[i].objectId
        })
      }
      that.setData({
        tags: tags
      })
      //随机生成随机标签颜色
      var colorArr = ["blue", "green", "red", "pink", "yellow"];
      var colorLen = colorArr.length;
      var newArr = [];
      var pre = null;
      var arrLen = that.data.tags.length;
      for (var i = 0; i < arrLen; i++) {
        while (random == pre) {
          var random = colorArr[Math.floor(Math.random() * colorLen)];
        }
        pre = random;
        newArr.push(random);
      }
      this.setData({
        randomColor: newArr
      })
    });




  },
  DeleteImg: function (e) {
    console.log(e)

  },

  //加载中函数，你可以直接调用
  handleLoadingStart() {
    $Toast({
      content: '上传中...',
      type: 'loading',
      duration: 0
    });
  },
  handleLoadingStop() {
    $Toast.hide()
  },
  oneChange(event) {
    this.setData({
      'oneChecked': event.detail.checked
    })
  },
  onChange(event) {
    const detail = event.detail;
    this.setData({
      ['tags[' + event.detail.name + '].checked']: detail.checked
    })

  },
  upload_datas: function () {
    var that = this;
    //构造pointer对象指向登陆的微信
    const pointer = Bmob.Pointer('_User');
    const poiID = pointer.set(app.globalData.authData.objectId)
    console.log('准备传输数据给用户：', app.globalData.authData.objectId)
    //构造relation对象指向当前选中的tag
    const relation = Bmob.Relation('label') // 需要关联的表
    var tagObjIds = []
    for (var i = 0; i < that.data.tags.length; i++) {
      var tag = that.data.tags[i]
      if (tag.checked) {
        console.log(tag.name)
        tagObjIds.push(tag.objectId)
      }
    }
    const relID = relation.add(tagObjIds)
    //查找数据表
    const query = Bmob.Query('Postings');
    //定义数据
    query.set('user', poiID);
    query.set("title", that.data.title);
    query.set("detail", that.data.content);
    query.set("tag", relID);
    query.set("imgs", that.data.file_urls)
    //上传
    query.save().then(res => {
      $Message({
        content: '上传成功！',
        type: 'success'
      });
      console.log(res)
      wx.switchTab({
        url: '../../pages/indexnew/indexnew'
      })
      that.handleLoadingStop()
    }).catch(err => {
      $Message({
        content: '上传失败！',
        type: 'error'
      });
      console.log(err)
      that.handleLoadingStop()
    })

  },
  upload: function () {
    //上传数据
    var that = this;
    //上传图片
    var file
    //判断是否有空数据
    if (that.data.title.length < 3) {
      console.log("title太短")
      $Message({
        content: '输入的标题太短！',
        type: 'error'
      });
      return;
    }
    else if (that.data.content.length < 10) {
      console.log("content太短")
      $Message({
        content: '输入的内容太短！',
        type: 'error'
      });
      return;
    }
    that.handleLoadingStart()
    if (that.data.files.length) {
      for (let item of that.data.files) {
        console.log(item)
        file = Bmob.File(app.globalData.userInfo.nickName + '.jpg', item);
      }
      file.save().then(res => {
        var file_urls = []
        for (let item of res) {
          var res_json = JSON.parse(item);
          file_urls.push(res_json.url)
          console.log('文件上传成功', res_json)
        }
        that.setData({
          file_urls: file_urls
        })
        that.upload_datas()
      })
    }
    else {
      that.upload_datas()
    }


  },
  inputTitle: function (e) {
    this.setData({
      title: e.detail.value
    })
  },
  inputDetail: function (e) {
    this.setData({
      content: e.detail.value,
      length: e.detail.value.length
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  // onShow: function() {
  //     var that = this;
  //     this.setData({
  //       num:content.length()
  //     })
  // },


  onBindBlur: function (event) {
    var text = event.detail.value;
    this.setData({
      num: text.length
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      // sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      count: 9 - that.data.files.length,
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },


})